<template>
  <div class="detail" ref="containerRef">
    <a-affix :target="(containerRef as HTMLElement)">
      <a-page-header :title="customerId ? '编辑需求' : '新增需求'" @back="back" class="head"> </a-page-header>
    </a-affix>

    <div class="form-content">
      <a-form ref="formRef" :model="form" :style="{ width: '800px' }" @submit="handleSubmit">
        <div class="form-item-title">基本信息</div>
        <a-form-item
          field="customer_id"
          label="关联用户"
          :rules="[{ required: true, message: '关联用户不能为空' }]"
          :validate-trigger="['change', 'input']"
          ><a-select
            :disabled="customerId"
            allow-search
            @popup-visible-change="changeVisible"
            style="width: 200px"
            v-model="form.customer_id"
            placeholder="请选择关联用户"
          >
            <a-option v-for="item in userOption" :value="item.value">{{ item.label }}</a-option>
          </a-select>
          <a-button style="margin-left: 10px" type="primary" @click="handleOpenCreate">
            <template #icon>
              <icon-plus />
            </template>
            <template #default>创建用户</template>
          </a-button>
          <template #extra>
            <div>还没有注册过的用户点击创建用户</div>
          </template>
        </a-form-item>
        <div class="form-item-title">需求信息</div>
        <a-form-item field="demandName" label="需求名称" :rules="[{ required: true, message: '需求名称不能为空' }]">
          <a-input v-model="form.demandName" :disabled="customerId" placeholder="请输入需求名称" allow-clear />
        </a-form-item>
        <a-form-item field="demandType" label="交稿类型" :rules="[{ required: true, message: '交稿类型必选' }]">
          <a-radio-group :disabled="customerId" v-model="form.demandType">
            <a-radio :value="2">单次任务</a-radio>
            <a-radio :value="1">重复任务</a-radio>
          </a-radio-group>
          <template v-if="form.demandType == '1'">
            <span style="margin-left: 20px">间隔交稿周期</span>
            <a-select :disabled="customerId" v-model="form.taskType" style="width: 120px; margin-left: 12px">
              <a-option value="1">日交</a-option>
              <a-option value="2">周交</a-option>
            </a-select>
          </template>
        </a-form-item>

        <a-form-item field="price" label="任务价格" :rules="[{ required: true, message: '任务价格不能为空' }]">
          <a-input-number style="width: 200px" v-model="form.price" placeholder="请输入单次任务价格" />
          <template #extra>
            <div>这里指单次任务价格</div>
          </template>
        </a-form-item>
        <a-form-item field="number" label="撰写数量" :rules="[{ required: true, message: '撰写数量不能为空' }]">
          <a-input-number style="width: 200px" v-model="form.number" placeholder="请输入撰写数量" />
        </a-form-item>
        <a-form-item
          v-if="form.demandType == 2"
          field="date"
          label="交稿时间"
          :rules="[{ required: true, message: '交稿时间不能为空' }]"
        >
          <a-date-picker :disabled="customerId" style="width: 200px" v-model="form.date" placeholder="请选择交稿时间" />
        </a-form-item>
        <a-form-item
          v-else
          field="dateRange"
          label="交稿时间"
          :rules="[{ required: true, message: '交稿时间不能为空' }]"
        >
          <a-range-picker :disabled="customerId" style="width: 300px" v-model="form.dateRange">
            <template #extra>
              <a-tag :checked="form.isLong" @check="handeChooseLong" checkable color="arcoblue">长期</a-tag>
              <!-- <a-button @click="handeChooseLong" type="outline">长期</a-button> -->
            </template>
          </a-range-picker>
        </a-form-item>
        <a-form-item field="editTimes" label="可修改次数" :rules="[{ required: true, message: '可修改次数不能为空' }]">
          <a-input-number style="width: 200px" v-model="form.editTimes" placeholder="请输入可修改次数" />
          <template #extra>
            <div>设置用户不满意稿件情况下，可修改的次数</div>
          </template>
        </a-form-item>
        <div class="form-item-title">客户需求说明</div>

        <a-form-item field="remarks" label="说明描述">
          <a-textarea v-model="form.remarks" placeholder="请输入描述信息" allow-clear />
        </a-form-item>
        <a-form-item field="" label="">
          <a-upload
            :auto-upload="false"
            action="/"
            :file-list="fileList"
            @change="handleUpload"
            @before-remove="beforeRemove"
          />
        </a-form-item>
        <a-form-item field="status" label="需求状态" :rules="[{ required: true, message: '需求状态必选' }]">
          <a-radio-group v-model="form.status">
            <a-radio value="1">进行中</a-radio>
            <a-radio value="2">已结束</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
      <a-space style="justify-content: center; margin-bottom: 10px">
        <a-button
          @click="
            () => {
              back()
              $refs.formRef.resetFields()
            }
          "
          >取消</a-button
        >
        <a-button type="primary" @click="handleSubmit">确认保存</a-button>
      </a-space>
    </div>
    <addUserModal ref="addUserModalRef"></addUserModal>
  </div>
</template>

<script setup lang="ts" name="DataDetail">
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { usePagination } from '@/hooks'
import { getCustomerDetail, uploadFile, getCustomerList, addDemandList, getDemandList, editDemandList } from '@/apis'
import addUserModal from './addUserModal.vue'
import { format, isSunday, startOfWeek, addDays } from 'date-fns'
import { Message } from '@arco-design/web-vue'
import { Modal } from '@arco-design/web-vue'

const route = useRoute()
const router = useRouter()

const addUserModalRef = ref()
const customerId = ref(route.query.id)

const formRef = ref<any>()
const dateRangeFormat = (dates: any) => {
  return `${dates[0].format('YYYY-MM-DD')} ~ ${dates[1].format('YYYY月MM-DD')}`
}
const loading = ref(false)
const containerRef = ref<HTMLElement | null>()
const form = reactive({
  customer_id: '',
  demandName: '',
  demandType: 2,
  taskType: '1',
  price: '',
  number: 3,
  date: '',
  dateRange: [],
  isLong: false,
  editTimes: '3',
  remarks: '',
  status: '1'
})
const back = () => {
  router.push({ path: '/demand-list' })
}
const handeChooseLong = (val) => {
  form.isLong = val
  if (val) {
    setTimeout(() => {
      if (form.dateRange[0]) {
        form.dateRange = [form.dateRange[0], '9999999999']
      } else {
        form.dateRange = [new Date(), '9999999999']
      }
    }, 10)
  } else {
    form.dateRange = []
  }
}
const fileList = ref([])
const handleUpload = (_, currentFile) => {
  let fileUrl = ''
  if (import.meta.env.MODE === 'development') {
    // 本地联调时使用
    fileUrl = 'https://push.aiseoword.com/'
  } else {
    // 线上环境使用
    fileUrl = import.meta.env.VITE_UPLOADED_FILE_BASE_URL
  }

  // 请求上传接口
  // 上传成功后，将返回的图片地址赋值给form.headimage
  const formData = new FormData()
  formData.append('file', currentFile.file)
  uploadFile(formData).then((res) => {
    if (res.code === 200) {
      fileList.value = [
        {
          uid: 1,
          name: currentFile.file.name,
          url: fileUrl + res.src
        }
      ]
      // form.headimage = fileUrl + res.src
    } else {
      Message.error(res.msg)
    }
  })
}
const userOption = ref([])
const changeVisible = (visible) => {
  if (visible) {
    initCustomerList()
  }
}
const initCustomerList = () => {
  getCustomerList({ limit: 1000 }).then((res) => {
    let resData = JSON.parse(res)
    userOption.value = (resData.result?.data || []).map((item) => {
      return {
        value: item.id,
        label: item.nickname + '-' + item.mobile
      }
    })
  })
}
// 判断是否为周末
const isWeek = () => {
  return new Promise((resolve) => {
    // 周交需要判断是否为周末
    if (form.taskType == '2') {
      //结束日期是否为周末
      if (form.dateRange[1] != '9999999999' && !isSunday(form.dateRange[1])) {
        const dayOfWeek = new Date(form.dateRange[1]).getDay()

        // 汉字映射数组
        const weekDays = ['日', '一', '二', '三', '四', '五', '六']
        const weekStart = startOfWeek(form.dateRange[1], { weekStartsOn: 0 }) // 0表示周日
        const nextSunday = addDays(weekStart, 7) // 通过加6天获取当前周的周日
        // 弹框提示是否继续
        Modal.confirm({
          // title: '确认取消当前任务',
          content: `周交任务，您当前选择交稿结束时间为周${weekDays[dayOfWeek]}，系统将为您自动调整到周日结尾，确定是否保存？`,
          okText: '确认',
          cancelText: '取消',
          onCancel: () => {
            Message.info('已取消操作, 请修改后重新提交')
            resolve(false)
          },
          onOk: async () => {
            end_time = format(nextSunday, 'yyyy-MM-dd 23:59:59')
            resolve(true)
          }
        })
      } else {
        resolve(true)
      }
    } else {
      resolve(true)
    }
  })
}
let end_time = ''
// 确认保存
const handleSubmit = async () => {
  const flag = await formRef.value?.validate()
  if (flag) return false
  let start_time = ''
  end_time = ''

  if (form.demandType == '1') {
    // 重复任务
    start_time = format(form.dateRange[0], 'yyyy-MM-dd 00:00:00')
    if (form.dateRange[1] === '9999999999') {
      // end_time = form.dateRange[1]
      end_time = '长期'
    } else {
      end_time = format(form.dateRange[1], 'yyyy-MM-dd 23:59:59')
    }
    let flag = await isWeek()
    if (!flag) {
      return false
    }
  } else {
    start_time = format(form.date, 'yyyy-MM-dd 00:00:00')
    end_time = format(form.date, 'yyyy-MM-dd 23:59:59')
  }
  let parmas = {
    name: form.demandName,
    descript: form.remarks,
    customer_id: form.customer_id,
    repeat: form.demandType,
    price: form.price,
    start_time,
    end_time,
    manuscripts_num: form.number,
    annex_url: '',
    status: form.status,
    reject_num_ok: form.editTimes,
    type: form.taskType
  }
  if (fileList.value.length > 0) {
    parmas.annex_url = JSON.stringify({
      src: fileList.value[0].url,
      name: fileList.value[0].name
    })
  }
  if (customerId.value) {
    // 编辑
    editDemandList({
      demand_id: customerId.value,
      ...parmas
    }).then((res) => {
      let resData = JSON.parse(res)
      if (resData.code === 200) {
        Message.success(resData.message || '保存成功')
        setTimeout(() => {
          router.push({ path: '/demand-list' })
        }, 300)
      } else {
        Message.error(resData.message || '保存失败')
      }
    })
  } else {
    // 新增
    addDemandList(parmas).then((res) => {
      let resData = JSON.parse(res)
      if (resData.code === 200) {
        Message.success(resData.message || '保存成功')
        setTimeout(() => {
          router.push({ path: '/demand-list' })
        }, 300)
      } else {
        Message.error(resData.message || '保存失败')
      }
    })
  }
}
const handleOpenCreate = () => {
  addUserModalRef.value.show()
}
onMounted(() => {
  changeVisible(true)
  if (customerId.value) {
    //初始化表单

    getDemandList({ demand_id: customerId.value }).then((res) => {
      let resData = JSON.parse(res)
      if (resData.code === 200) {
        let current = resData.result.data?.[0] || {}
        form.customer_id = current.customer_id
        form.demandName = current.name
        form.demandType = current.repeat
        form.taskType = current.type
        form.price = +current.price
        form.number = current.manuscripts_num
        form.date = current.start_time * 1000
        form.dateRange = [new Date(current.start_time * 1000), new Date(current.end_time * 1000)]
        form.isLong = current.end_time === '9999999999'
        form.editTimes = current.reject_num_ok
        form.remarks = current.descript
        form.status = current.status
        if (current.annex_url && current.annex_url != ' ') {
          let FileData = JSON.parse(current.annex_url)
          fileList.value = [
            {
              uid: 1,
              name: FileData.name,
              url: FileData.src
            }
          ]
        }
        if (current.end_time == '9999999999') {
          form.dateRange[1] = '9999999999'
        }
      }
    })
  }
})
</script>

<style lang="scss" scoped>
.detail {
  overflow: auto;
  height: 100%;
  // display: flex;
  // flex-direction: column;
  .head {
    background: var(--color-bg-1);
  }
  .item {
    margin: $margin;
    background: var(--color-bg-1);
    border-radius: 2px;
  }
  .form-content {
    // flex: 1;
    overflow: hidden;
    margin: $margin;
    background: var(--color-bg-1);
    padding: $padding;
    padding-bottom: 0;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    .form-item-title {
      font-weight: bold;
      margin-bottom: 20px;
      &::before {
        content: '';
        width: 2px;
        height: 8px;
        background: #1e9fff;
        display: inline-block;
        margin-right: 4px;
      }
    }
  }
}
</style>
